package event

import (
	"reflect"
	"strings"
)

type Handler func(v interface{}, args ...interface{})

type Bus map[string][]Handler

var bus Bus

func init() {
	bus = make(Bus)
}

func NewBus() Bus {
	return make(Bus)
}

// Sub 订阅事件，多个人可以同时订阅同一个事件
func (bus Bus) Sub(name string, handler Handler) {
	eventNames := strings.Split(name, " ")
	for _, eventName := range eventNames {
		bus[eventName] = append(bus[eventName], handler)
	}
}

// Pub 同步事件分发，必须等待上一个完成后才能执行下一个
func (bus Bus) Pub(name string, data interface{}, args ...interface{}) {
	handlers, ok := bus[name]
	if ok {
		for _, handler := range handlers {
			handler(data, args...)
		}
	}
}

// PubAsync 异步事件分发
func (bus Bus) PubAsync(name string, data interface{}, args ...interface{}) {
	handlers, ok := bus[name]
	if ok {
		for _, handler := range handlers {
			go func(hd Handler) {
				hd(data, args...)
			}(handler)
		}
	}
}

func Sub(name string, handler Handler) {
	bus.Sub(name, handler)
}

func Pub(name string, data interface{}, args ...interface{}) {
	bus.Pub(name, data, args...)
}
func PubAsync(name string, data interface{}, args ...interface{}) {
	bus.PubAsync(name, data, args...)
}
func GetArg(ptr interface{}, args []interface{}) int {
	for i, arg := range args {
		if reflect.TypeOf(arg) == reflect.ValueOf(ptr).Elem().Type() {
			//设置ptr的值为arg
			reflect.ValueOf(ptr).Elem().Set(reflect.ValueOf(arg))
			return i
		}
	}
	return -1
}
func GetArgByIndex(ptr interface{}, args []interface{}, index int) int {
	if index < len(args) {
		arg := args[index]
		if reflect.TypeOf(arg) == reflect.ValueOf(ptr).Elem().Type() {
			//设置ptr的值为arg
			reflect.ValueOf(ptr).Elem().Set(reflect.ValueOf(arg))
			return index
		}
	}
	return -1
}
